package net.keebook.webapp.bean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.inject.Inject;

import org.apache.log4j.Logger;

import net.keebook.webapp.dao.SettingDao;
import net.keebook.webapp.entity.Setting;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.Messages;


@ManagedBean
@RequestScoped
public class SettingsBean {
	private String timezone;
	private Boolean passwordLogin;
	private Boolean googleLogin;
	private Boolean facebookLogin;
	private Boolean twitterLogin;
	private Boolean allowSignup;
	private Boolean smtpAuth;
	private String smtpHost;
	private Long smtpPort;
	private String smtpUser;
	private String smtpPass;
	private String publicUrl;
	private String senderAddress;
	private Boolean smtpEnable;
	private String facebookAppId;
	private String facebookAppSecret;
	private String googleClientId;
	private String googleClientSecret;
	private String twitterConsumerKey;
	private String twitterConsumerSecret;
	
	@Inject
	private SettingDao settingDao;
	private SessionModel sessionModel;
	
	@PostConstruct
	public void init() throws IOException {
		setSessionModel(SessionModel.getInstance(FacesContext.getCurrentInstance()));
		
		if (!getSessionModel().getAdmin())  {
			Logger.getLogger(this.getClass()).warn("Forbidden access to bean from userId="+getSessionModel().getUserId());
			FacesContext.getCurrentInstance().getExternalContext().redirect("403.xhtml");
			return;
		}
		
		List<Setting> settings = getSettingDao().getList();
		for (Setting s : settings) {
			switch (s.getId()) {
				case PASSWORD_LOGIN:
					setPasswordLogin(s.getBoolean());
					break;
				case FACEBOOK_LOGIN:
					setFacebookLogin(s.getBoolean());
					break;
				case GOOGLE_LOGIN:
					setGoogleLogin(s.getBoolean());
					break;
				case TWITTER_LOGIN:
					setTwitterLogin(s.getBoolean());
					break;
				case ALLOW_SIGNUP:
					setAllowSignup(s.getBoolean());
					break;
				case PUBLIC_URL:
					setPublicUrl(s.getValue());
					break;
				case SMTP_AUTH:
					setSmtpAuth(s.getBoolean());
					break;
				case SMTP_HOST:
					setSmtpHost(s.getValue());
					break;
				case SMTP_PORT:
					setSmtpPort(s.getLong());
					break;
				case SMTP_USERNAME:
					setSmtpUser(s.getValue());
					break;
				case SMTP_PASSWORD:
					setSmtpPass(s.getValue());
					break;
				case SYSTEM_TIMEZONE:
					setTimezone(s.getValue());
					break;
				case SMTP_SENDER_ADDRESS:
					setSenderAddress(s.getValue());
					break;
				case SMTP_ENABLE:
					setSmtpEnable(s.getBoolean());
					break;
				case FACEBOOK_APP_ID:
					setFacebookAppId(s.getValue());
					break;
				case FACEBOOK_APP_SECRET:
					setFacebookAppSecret(s.getValue());
					break;
				case GOOGLE_CLIENT_ID:
					setGoogleClientId(s.getValue());
					break;
				case GOOGLE_CLIENT_SECRET:
					setGoogleClientSecret(s.getValue());
					break;
				case TWITTER_CONSUMER_KEY:
					setTwitterConsumerKey(s.getValue());
					break;
				case TWITTER_CONSUMER_SECRET:
					setTwitterConsumerSecret(s.getValue());
					break;
			}
		}
	}
	
	public List<SelectItem> getTimezones() {
		List<SelectItem> result = new ArrayList<SelectItem>();
		String[] ids = TimeZone.getAvailableIDs();
		for (String id : ids) {
			TimeZone tz = TimeZone.getTimeZone(id);
			int rawOffset = tz.getRawOffset();
		    int hour = rawOffset / (60*60*1000);
		    int min = Math.abs(rawOffset / (60*1000)) % 60;
		    
		    String time = (hour >= 0 ? "+" : "-") + (Math.abs(hour)) + ":" + (min < 9 ? "0"+min : min);
			String s = "(UTC"+time+") "+ TimeZone.getTimeZone(id).getDisplayName(Locale.US) +" ("+id+")";
		    
			result.add(new SelectItem(id, s));
		}
		return result;
	}
	
	public void apply() throws IOException {
		if (!getSessionModel().getAdmin())  {
			Logger.getLogger(this.getClass()).warn("Forbidden access to bean from userId="+getSessionModel().getUserId());
			FacesContext.getCurrentInstance().getExternalContext().redirect("403.xhtml");
			return;
		}
		
		List<Setting> settings = getSettingDao().getList();
		for (Setting s : settings) {
			switch (s.getId()) {
				case PASSWORD_LOGIN:
					s.setValue(getPasswordLogin());
					break;
				case FACEBOOK_LOGIN:
					s.setValue(getFacebookLogin());
					break;
				case GOOGLE_LOGIN:
					s.setValue(getGoogleLogin());
					break;
				case TWITTER_LOGIN:
					s.setValue(getTwitterLogin());
					break;
				case SYSTEM_TIMEZONE:
					s.setValue(getTimezone());
					break;
				case PUBLIC_URL:
					s.setValue(getPublicUrl());
					break;
				case ALLOW_SIGNUP:
					s.setValue(getAllowSignup());
					break;
				case SMTP_AUTH:
					s.setValue(getSmtpAuth());
					break;
				case SMTP_USERNAME:
					s.setValue(getSmtpUser());
					break;
				case SMTP_PASSWORD:
					s.setValue(getSmtpPass());
					break;
				case SMTP_PORT:
					s.setValue(getSmtpPort());
					break;
				case SMTP_SENDER_ADDRESS:
					s.setValue(getSenderAddress());
					break;
				case SMTP_ENABLE:
					s.setValue(getSmtpEnable());
					break;
				case FACEBOOK_APP_ID:
					s.setValue(getFacebookAppId());
					break;
				case FACEBOOK_APP_SECRET:
					s.setValue(getFacebookAppSecret());
					break;
				case GOOGLE_CLIENT_ID:
					s.setValue(getGoogleClientId());
					break;
				case GOOGLE_CLIENT_SECRET:
					s.setValue(getGoogleClientSecret());
					break;
				case TWITTER_CONSUMER_KEY:
					s.setValue(getTwitterConsumerKey());
					break;
				case TWITTER_CONSUMER_SECRET:
					s.setValue(getTwitterConsumerSecret());
					break;
			}
			getSettingDao().update(s);
		}
		FacesContext.getCurrentInstance().getExternalContext().redirect("settings.xhtml?msg="+Messages.SETTINGS_APPLIED);
	}
	
	public Boolean getPasswordLogin() {
		return passwordLogin;
	}
	public void setPasswordLogin(Boolean passwordLogin) {
		this.passwordLogin = passwordLogin;
	}
	public Boolean getGoogleLogin() {
		return googleLogin;
	}
	public void setGoogleLogin(Boolean googleLogin) {
		this.googleLogin = googleLogin;
	}
	public Boolean getFacebookLogin() {
		return facebookLogin;
	}
	public void setFacebookLogin(Boolean facebookLogin) {
		this.facebookLogin = facebookLogin;
	}

	public SettingDao getSettingDao() {
		return settingDao;
	}

	public void setSettingDao(SettingDao settingDao) {
		this.settingDao = settingDao;
	}

	public String getTimezone() {
		return timezone;
	}

	public void setTimezone(String timezone) {
		this.timezone = timezone;
	}

	public Boolean getAllowSignup() {
		return allowSignup;
	}

	public void setAllowSignup(Boolean allowSignup) {
		this.allowSignup = allowSignup;
	}

	public Boolean getSmtpAuth() {
		return smtpAuth;
	}

	public void setSmtpAuth(Boolean smtpAuth) {
		this.smtpAuth = smtpAuth;
	}

	public String getSmtpHost() {
		return smtpHost;
	}

	public void setSmtpHost(String smtpHost) {
		this.smtpHost = smtpHost;
	}

	public Long getSmtpPort() {
		return smtpPort;
	}

	public void setSmtpPort(Long smtpPort) {
		this.smtpPort = smtpPort;
	}

	public String getSmtpUser() {
		return smtpUser;
	}

	public void setSmtpUser(String smtpUser) {
		this.smtpUser = smtpUser;
	}

	public String getSmtpPass() {
		return smtpPass;
	}

	public void setSmtpPass(String smtpPass) {
		this.smtpPass = smtpPass;
	}

	public String getPublicUrl() {
		return publicUrl;
	}

	public void setPublicUrl(String publicUrl) {
		this.publicUrl = publicUrl;
	}

	public String getSenderAddress() {
		return senderAddress;
	}

	public void setSenderAddress(String senderAddress) {
		this.senderAddress = senderAddress;
	}

	public SessionModel getSessionModel() {
		return sessionModel;
	}

	public void setSessionModel(SessionModel sessionModel) {
		this.sessionModel = sessionModel;
	}

	public Boolean getSmtpEnable() {
		return smtpEnable;
	}

	public void setSmtpEnable(Boolean smtpEnable) {
		this.smtpEnable = smtpEnable;
	}

	public String getFacebookAppId() {
		return facebookAppId;
	}

	public void setFacebookAppId(String facebookAppId) {
		this.facebookAppId = facebookAppId;
	}

	public String getFacebookAppSecret() {
		return facebookAppSecret;
	}

	public void setFacebookAppSecret(String facebookAppSecret) {
		this.facebookAppSecret = facebookAppSecret;
	}

	public String getGoogleClientId() {
		return googleClientId;
	}

	public void setGoogleClientId(String googleClientId) {
		this.googleClientId = googleClientId;
	}

	public String getGoogleClientSecret() {
		return googleClientSecret;
	}

	public void setGoogleClientSecret(String googleClientSecret) {
		this.googleClientSecret = googleClientSecret;
	}

	public Boolean getTwitterLogin() {
		return twitterLogin;
	}

	public void setTwitterLogin(Boolean twitterLogin) {
		this.twitterLogin = twitterLogin;
	}

	public String getTwitterConsumerKey() {
		return twitterConsumerKey;
	}

	public void setTwitterConsumerKey(String twitterConsumerKey) {
		this.twitterConsumerKey = twitterConsumerKey;
	}

	public String getTwitterConsumerSecret() {
		return twitterConsumerSecret;
	}

	public void setTwitterConsumerSecret(String twitterConsumerSecret) {
		this.twitterConsumerSecret = twitterConsumerSecret;
	}
}
